# -*- coding=utf-8
from django.http import JsonResponse
from qcloud_cos import CosConfig, CosServiceError
from qcloud_cos import CosS3Client
import sys
import os
import json, pprint
import traceback
from django.conf import settings
from sts.sts import Sts


def create_bucket(bucket, region="ap-chengdu"):
    # 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
    secret_id = settings.TENCENT_COS_SECRET_ID  # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
    secret_key = settings.TENCENT_COS_SECRET_KEY  # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
    token = None  # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config)
    client.create_bucket(
        Bucket=bucket,
        ACL='public-read',
    )
    # 使用腾讯云COS SDK推荐的CORS配置格式
    try:
        # 确保桶已创建成功后再配置CORS
        cors_config = {
            'CORSRule': [
                {
                    'AllowedOrigin': ['*'],
                    'AllowedMethod': ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'],
                    'AllowedHeader': ['*'],
                    'ExposeHeader': ['ETag', 'Content-Type', 'x-cos-request-id'],
                    'MaxAgeSeconds': 500
                }
            ]
        }
        # 使用展开方式传递配置
        response = client.put_bucket_cors(
            Bucket=bucket,
            CORSConfiguration=cors_config
        )
        print(f"CORS配置成功: {response}")
    except Exception as e:
        # 记录CORS配置错误但不中断创建桶的流程
        print(f"CORS配置错误: {str(e)}")


def check_file(bucket, region, key):
    # 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
    secret_id = settings.TENCENT_COS_SECRET_ID  # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
    secret_key = settings.TENCENT_COS_SECRET_KEY  # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
    token = None  # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config)
    data = client.head_object(
        Bucket=bucket,
        Key=key)
    return data


def upload_file(bucket, region, file_object, key):
    secret_id = settings.TENCENT_COS_SECRET_ID
    secret_key = settings.TENCENT_COS_SECRET_KEY
    token = None
    scheme = 'https'
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config)

    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_object,
        Key=key,
    )
    # 上传成功之后返回图片路径 https://tyw226-1381688644.cos.ap-shanghai.myqcloud.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250910112618_2_4.png
    return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, region, key)


def delete_file(bucket, region, key):
    secret_id = settings.TENCENT_COS_SECRET_ID
    secret_key = settings.TENCENT_COS_SECRET_KEY
    token = None
    scheme = 'https'
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config)
    client.delete_object(
        Bucket=bucket,
        Key=key,
    )


def delete_file_list(bucket, region, key_list):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_SECRET_ID,
                       SecretKey=settings.TENCENT_COS_SECRET_KEY)
    client = CosS3Client(config)
    objects = key_list
    client.delete_objects(
        Bucket=bucket,
        Delete=objects,
    )


def credential(bucket, region):
    config = {
        # 请求URL，域名部分必须和domain保持一致
        # 使用外网域名时：https://sts.tencentcloudapi.com/
        # 使用内网域名时：https://sts.internal.tencentcloudapi.com/
        'url': 'https://sts.tencentcloudapi.com/',
        # 域名，非必须，默认为 sts.tencentcloudapi.com
        # 内网域名：sts.internal.tencentcloudapi.com
        'domain': 'sts.tencentcloudapi.com',
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': settings.TENCENT_COS_SECRET_ID,
        # 固定密钥
        'secret_key': settings.TENCENT_COS_SECRET_KEY,
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': ['*'],
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 存储桶级别权限
            'name/cos:GetBucket',
            'name/cos:ListBucket',
            'name/cos:HeadBucket',
            # 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
        ],
        # 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
        # "condition": {
        #     "ip_equal": {
        #         "qcs:ip": [
        #             "10.217.182.3/24",
        #             "111.21.33.72/24",
        #         ]
        #     }
        # }
    }

    try:
        sts = Sts(config)
        result_list = sts.get_credential()
        return result_list
    except Exception as e:
        print(f"获取临时密钥失败: {e}")
        return None


def delete_bucket(bucket, region):
    """ 删除桶 """
    # 删除桶内所有文件
    # 删除桶内所有碎片文件
    # 删除桶
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_SECRET_ID,SecretKey=settings.TENCENT_COS_SECRET_KEY)
    client = CosS3Client(config)
    try:
        # 找到桶内所有文件,腾讯云一次最多只能拿取1000个文件,需要循环处理
        while True:
            part_objects=client.list_objects(Bucket=bucket)
            contents=part_objects.get('Contents')
            if not contents:
                break
            # 批量删除
            objects={
                'Quiet':'true',
                'Object':[{'Key':item['Key']}for item in contents]
            }
            client.delete_objects(bucket, objects)

            if part_objects['IsTruncated']=='false':
                break

        # 找到碎片文件&删除,腾讯云一次最多只能拿取1000个文件,需要循环处理
        while True:
            part_uploads = client.list_multipart_uploads(Bucket=bucket)
            uploads=part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'],item['UploadId'])
            if part_objects['IsTruncated']=='false':
                break

        # 删除桶
        client.delete_bucket(Bucket=bucket)
    except CosServiceError as e:
        pass